package com.ifp.opengate.boot.validator;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.stereotype.Component;

import com.ifp.core.log.Trace;
import com.ifp.core.util.SpringContextsUtil;
import com.ifp.opengate.boot.bean.ValidatorForm;
import com.ifp.opengate.boot.exception.AccessControlException;
import com.ifp.opengate.boot.validator.constants.ValidatorConstants;

/**
 * <p>
 * 验证工具
 * </P>
 *
 * @author zhuzh@belink.com
 * @version 0.0.1
 * @className ValidatorTool
 * @sine 2020/4/25 23:09
 */
@Component
public final class ValidatorTool {
    public void validator(ValidatorForm validatorForm, Object object) throws IllegalAccessException {
        // 必填校验,不管是否打开验证开关都进行校验
        Trace.logInfo(Trace.MODULE_COMMON, "参数{}类型{}", validatorForm.getParamName(), validatorForm.getIsNeed());
        if (!"fixedVal".equals(validatorForm.getCheckRule())) {
            if ("M".equals(validatorForm.getIsNeed()) && !"headToBody".equals(validatorForm.getCheckRule())) {
                if (object == null || "".equals(object)) {
                    throw new AccessControlException(ValidatorConstants.DEFAULT_ERROR_CODE,
                        "请上送必填参数" + validatorForm.getParamName());
                }
            } else if ("C".equals(validatorForm.getIsNeed())) {
                // TODO: 依据条件判断,二阶段
            } else {
                // O或其他不做校验
            }
        }
        // 长度检验
        /*if((object != null && !"".equals(object)) && StringUtils.isNotBlank(validatorForm.getParamLength())) {
        	Integer filedMaxLength = null;
        	try {
        		filedMaxLength = Integer.valueOf(validatorForm.getParamLength());
        	} catch (NumberFormatException e) {
        		Trace.logError(Trace.MODULE_COMMON, "参数长度配置出错：{} 长度：{}", e);;
        	}
        }*/
        // 是否校验
        if ("1".equals(validatorForm.getParamIsCheck())) {
            try {
                ValidateService validateService =
                    (ValidateService)SpringContextsUtil.getBean(validatorForm.getCheckRule() + "ValidateServiceImpl");
                validateService.validate(object, validatorForm);
            } catch (NoSuchBeanDefinitionException e) {
                // headToBody没有对应校验器
                Trace.logInfo(Trace.MODULE_COMMON, e.getMessage());
            } catch (Exception e) {
                throw e;
            }
        }
    }
}
